<template>
  <div>
    <div class="login-wrap" v-if="status == 1">
      <div class="login-title">
        <img src="@/assets/login/logo@2x.png" alt="" />
      </div>
      <div class="login">
        <Tabs value="name1" class="login-tags" @on-click="switchTabHandle">
          <TabPane label="验证码登录" name="name1">
            <Form ref="usernameLoginForm" :model="form" :rules="rules" class="form">
              <FormItem prop="username">
                <Input
                  v-model="form.username"
                  prefix="ios-person-outline"
                  size="large"
                  clearable
                  placeholder="请输入账号/手机/邮箱"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="code" class="code-input">
                <Input
                  v-model="form.code"
                  prefix="ios-lock-outline"
                  size="large"
                  placeholder="请输入验证码"
                  autocomplete="off"
                />
                <span class="get-code" @click="getCode">{{
                  codeTime.status ? `${codeTime.time}s后重新获取` : "获取验证码"
                }}</span>
              </FormItem>
            </Form>
            <Row>
              <Button
                class="login-btn"
                type="primary"
                size="large"
                :loading="loading"
                @click="submitLogin('code')"
                long
              >
                登录
              </Button>
            </Row>
          </TabPane>
          <TabPane label="密码登录" name="name2">
            <Form ref="usernameLoginForm" :model="form" :rules="rules" class="form">
              <FormItem prop="username">
                <Input
                  v-model="form.username"
                  prefix="ios-person-outline"
                  size="large"
                  clearable
                  placeholder="请输入账号/手机/邮箱"
                  autocomplete="off"
                />
              </FormItem>
              <FormItem prop="password">
                <Input
                  type="password"
                  v-model="form.password"
                  prefix="ios-lock-outline"
                  size="large"
                  password
                  placeholder="请输入密码"
                  autocomplete="off"
                />
              </FormItem>
            </Form>
            <Row>
              <Button
                class="login-btn"
                type="primary"
                size="large"
                :loading="loading"
                @click="submitLogin('password')"
                long
              >
                登录
              </Button>
            </Row>
          </TabPane>
        </Tabs>
        <div class="login-way">
          <span class="wx" @click="wxLogin">微信登录</span>
          <span class="divider">|</span>
          <span class="qq" @click="qqLogin" id="qqLoginBtn">QQ登录</span>
          <span class="divider">|</span>
          <span class="wb" @click="wbLogin">微博登录</span>
        </div>
        <div class="terms">
          <span>注：未注册手机验证后自动登录 注册即代表同意《服务条款》</span>
        </div>
      </div>
    </div>
    <ChooseRole v-else-if="status == 2" @chooseRole="chooseRole"></ChooseRole>
    <Binding
      :userType="params.userType"
      v-else-if="status == 3"
      @changeStatus="changeStatus"
    ></Binding>
    <Person
      v-else-if="status == 4"
      :userType="params.userType"
      @backHandle="backHandle"
      @completeHandle="completeHandle"
    ></Person>
    <Sport v-else @sportHandle="sportHandle"></Sport>
    <!-- <wxlogin
      :appid="app_id"
      :scope="'snsapi_login'"
      theme="black"
      :redirect_uri="
        encodeURIComponent(
          'https://buyer-api.westts.cn/buyer/passport/connect/connect/callback/WEIXIN'
        )
      "
      state=""
    >
    </wxlogin> -->
  </div>
</template>

<script>
import QC from "qc";
// import wxlogin from "vue-wxlogin";
import Cookies from "js-cookie";
import { login, getCode, codeLogin, registered, userInfo } from "../../api/otwoo.js";
import { loginCallback } from "@/api/login.js";
import Binding from "./bindingStudentId.vue";
import ChooseRole from "./chooseRole.vue";
import Person from "./person.vue";
import Sport from "./sport.vue";
import Storage from "@/plugins/storage.js";
import bus from "@/libs/bus.js";
export default {
  components: {
    Binding,
    Person,
    ChooseRole,
    Sport,
    // wxlogin,
  },
  data() {
    return {
      way: "code",
      codeTime: { time: 60, status: false }, //重新获取验证码时间
      loading: false, // 加载状态
      status: 1,
      form: {
        // 表单数据
        username: "",
        password: "",
        code: "",
      },
      rules: {
        // 验证规则
        username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
        code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
      },
      //注册信息
      params: {
        number: "",
        userType: "",
        username: "",
        bmi: "",
        birthday: "",
        face: "",
        height: "",
        mobilePhone: "",
        nickName: "",
        sex: "",
        targetType: "",
        weight: "",
      },
      userInfo: "",
    };
  },
  mounted() {
    this.init();
    localStorage.clear();
  },
  methods: {
    // 初始化数据
    init() {
      let exists = this.$route.query.exists;
      if (exists == "false") {
        let unionType = this.$route.query.unionType;
        let label = decodeURIComponent(unionType);
        this.$Message.warning({
          content: `该${label}未绑定平台账号，请先绑定`,
          duration: 5,
        });
      } else {
        let uuid = this.$route.query.state;
        if (uuid) {
          Storage.setItem("uuid", uuid);
          loginCallback(uuid).then((res) => {
            if (res.success) {
              this.saveToken(res.result);
            }
          });
        }
      }
    },
    chooseRole(obj) {
      this.status = obj.num;
      if (obj.role === "Student") {
        this.params.userType = "0";
      } else if (obj.role === "Teacher") {
        this.params.userType = "1";
      } else {
        this.params.userType = "2";
      }
    },
    //点击下一步
    changeStatus(obj) {
      this.status = obj.num;
      if (obj.params) {
        this.params.number = obj.params.number;
      }
    },
    //返回到上一步
    backHandle(num) {
      this.status = num;
    },
    //点击完成
    completeHandle(obj) {
      this.status = obj.num;
      this.params.username = this.form.username;
      this.params.mobilePhone = this.form.mobilePhone;
      this.params.birthday = obj.personInformation.born;
      this.params.face = obj.personInformation.face;
      this.params.height = obj.personInformation.height;
      this.params.nickName = obj.personInformation.nickName;
      this.params.sex = obj.personInformation.sex;
      this.params.weight = obj.personInformation.weight;
      if (this.params.weight != "" && this.params.height != "") {
        this.params.bmi = (
          this.params.weight /
          ((this.params.height / 100) * (this.params.height / 100))
        ).toFixed(2);
      } else {
        this.params.bmi = "";
      }
    },
    //注册
    sportHandle(idStr) {
      this.params.targetType = idStr;
      registered(this.params).then((res) => {
        if (res.success) {
          if (res.result.exists) {
            this.$Message.success(res.message);
            this.userInfo = res.result;
            this.afterLogin(res);
            Cookies.set("userInfoManager", JSON.stringify(this.userInfo));
            this.$router.push({
              path: "/home",
            });
          } else {
            this.$Message.error(res.message);
          }
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    afterLogin(res) {
      // 登录成功后处理
      console.log(res.result.accessToken);
      let accessToken = res.result.accessToken;
      let refreshToken = res.result.refreshToken;
      // this.setStore("accessToken", accessToken);
      // this.setStore("refreshToken", refreshToken);
      localStorage.setItem("accessToken", res.result.accessToken);
      localStorage.setItem("refreshToken", res.result.refreshToken);
    },
    getUserInfo() {
      userInfo()
        .then((res) => {
          if (res.code == 200) {
            this.userInfo = res.result;
            Storage.setItem("userInfo", JSON.stringify(res.result));
            localStorage.setItem("userInfo", JSON.stringify(res.result));
            let name = sessionStorage.getItem("name") || "home";
            this.$router.push(`/${name}`);
          } else {
            Storage.setItem("accessToken", null);
            Storage.setItem("refreshToken", null);
            localStorage.setItem("accessToken", null);
            localStorage.setItem("refreshToken", null);
            Cookies.set("userInfoManager", null);
            this.loading = false;
            this.$Message.error("登录失败,请重试！");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    submitLogin(way) {
      this.way = way;
      // 登录操作
      if (this.way == "password" && this.form.username && this.form.password) {
        this.loading = true;
        this.$refs.usernameLoginForm.validate((valid) => {
          if (valid) {
            Storage.setItem("clientType", "PC");
            login({
              username: this.form.username,
              password: this.md5(this.form.password),
            })
              .then((res) => {
                if (res && res.success) {
                  if (res.result.exists) {
                    this.saveToken(res.result);
                  }
                } else {
                  this.$Message.error("登录失败");
                  this.loading = false;
                }
              })
              .catch(() => {
                this.loading = false;
              });
          }
        });
      } else if (this.way == "code" && this.form.username && this.form.code) {
        this.loading = true;
        codeLogin({ mobile: this.form.username, code: this.form.code })
          .then((res) => {
            if (res && res.success) {
              if (res.result.exists) {
                Cookies.set("userInfoManager", JSON.stringify(res.result));
                this.afterLogin(res);
                this.getUserInfo();
              } else {
                this.status = 2;
              }
            } else {
              this.loading = false;
            }
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        this.$Message.error("请输入完整的用户信息");
      }
    },
    // 保存token
    saveToken(res) {
      Storage.setItem("accessToken", res.accessToken);
      Storage.setItem("refreshToken", res.refreshToken);
      localStorage.setItem("accessToken", res.accessToken);
      localStorage.setItem("refreshToken", res.refreshToken);
      Cookies.set("userInfoManager", JSON.stringify(res));
      this.getUserInfo();
    },
    //tab页切换
    switchTabHandle() {
      this.form.username = "";
      this.form.password = "";
      this.form.code = "";
    },
    //获取手机验证码
    getCode() {
      if (this.form.username != "") {
        if (!this.codeTime.status) {
          //倒计时
          this.codeTime.status = true;
          let timer = setInterval(() => {
            this.codeTime.time = this.codeTime.time - 1;
            if (this.codeTime.time == 0) {
              clearInterval(timer);
              this.codeTime.time = 60;
              this.codeTime.status = false;
            }
          }, 1000);
          //发送获取验证码请求
          getCode({
            mobile: this.form.username,
            verificationEnums: "LOGIN",
          }).then((res) => {
            if (res.code == 80201) {
              this.$Message.success(res.message);
            }
          });
        }
      } else {
        this.$Message.error("请先输入手机号");
      }
    },
    //唤醒wx登录
    wxLogin() {
      console.log("唤起wx");
    },
    //唤醒qq登录
    qqLogin() {
      localStorage.setItem("loginForm", "login");
      window.open(
        "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=102028269&redirect_uri=https://buyer-api.westts.cn/buyer/passport/connect/connect/callback/QQ&state=2e73ea5f596f1180ad5289e699aec65c&scope=get_user_info",
        "_self"
      );
      // QC.Login({
      //   btnId: "qqLoginBtn",
      // });
    },
    // 唤醒wb登录
    wbLogin() {
      console.log("唤起wb");
    },
  },
};
</script>

<style lang="scss" scoped>
.login-wrap {
  width: 100%;
  height: 100vh;
  background: url("../../assets/login/beij@2x.png") no-repeat;
  background-color: #f0f2f5;
  background-size: cover;
  display: flex;
  flex-direction: column; 
  align-items: center;
  overflow-y: auto;

  .verify-con {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10000;
  }
  .login-title {
    background-color: none;
    margin-top: calc(120 / 1920 * 100vw);
    > img {
      width: calc(390 / 1920 * 100vw);
      height: calc(40 / 1920 * 100vw);
    }
  }
  .login {
    width: calc(502 / 1920 * 100vw);
    background: #ffffff;
    border-radius: calc(10 / 1920 * 100vw);
    padding: calc(51 / 1920 * 100vw) calc(56 / 1920 * 100vw) calc(20 / 1920 * 100vw)
      calc(52 / 1920 * 100vw);
    margin-top: calc(20 / 1920 * 100vw);
    :deep(.login-tags) {
      font-size: calc(20 / 1920 * 100vw);
      font-family: Source Han Sans SC;
      font-weight: bold;
      color: #3b3b3b;
      line-height: calc(57 / 1920 * 100vw);
      .form {
        margin-top: calc(16 / 1920 * 100vw);
        .code-input {
          position: relative;
          .get-code {
            font-size: calc(16 / 1920 * 100vw);
            font-family: Source Han Sans SC;
            font-weight: 400;
            color: #ea3f47;
            position: absolute;
            right: calc(17 / 1920 * 100vw);
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
          }
        }
        .ivu-input-wrapper {
          .ivu-input-large {
            height: calc(54 / 1920 * 100vw);
            padding-left: calc(49 / 1920 * 100vw);
            padding-right: calc(30 / 1920 * 100vw);
            font-size: calc(16 / 1920 * 100vw);
            font-family: Source Han Sans SC;
            font-weight: 400;
            /*color: #cfcfcf;*/
          }
        }
      }
      .ivu-btn-large {
        height: calc(54 / 1920 * 100vw);
        margin-top: calc(16 / 1920 * 100vw);
        font-size: calc(20 / 1920 * 100vw);
        font-family: Source Han Sans SC;
        font-weight: 400;
      }
    }
    //覆盖iviewui样式
    :deep(.ivu-tabs-nav) {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
    :deep(.ivu-tabs-ink-bar) {
      height: calc(3 / 1920 * 100vw);
    }
    :deep(.ivu-tabs-tab) {
      font-size: calc(20 / 1920 * 100vw);
      padding: calc(17 / 1920 * 100vw) 0px;
      width: 50%;
      margin: 0px;
      text-align: center;
      cursor: pointer;
    }
    :deep(.ivu-tabs-tab:hover) {
      color: #3b3b3b;
    }
    :deep(.ivu-input-prefix, .ivu-input-suffix) {
      display: flex;
      align-items: center;
      justify-content: center;
      width: calc(46 / 1920 * 100vw);
    }
    :deep(.ivu-input-suffix) {
      display: flex;
      align-items: center;
      justify-content: center;
      width: calc(46 / 1920 * 100vw);
    }
    :deep(.ivu-input-wrapper-large .ivu-input-icon) {
      height: 100%;
      width: calc(46 / 1920 * 100vw);
      line-height: calc(54 / 1920 * 100vw);
    }
  }
}

.login-way {
  width: 100%;
  font-size: calc(16 / 1920 * 100vw);
  font-family: Source Han Sans SC;
  font-weight: 400;
  color: #333333;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: calc(30 / 1920 * 100vw);
  line-height: calc(20 / 1920 * 100vw);
  .wx,
  .qq,
  .wb {
    display: block;
    cursor: pointer;
  }
  .divider {
    margin: 0px calc(10 / 1920 * 100vw);
  }
}
.terms {
  font-size: calc(14 / 1920 * 100vw);
  font-family: Source Han Sans SC;
  font-weight: 400;
  color: #d2d2d3;
  text-align: center;
  line-height: calc(30 / 1920 * 100vw);
  margin-top: calc(14 / 1920 * 100vw);
}
</style>
